package org.example.myleet.p654;

import org.example.myleet.Utils.TreeNode;

public class Solution {
    public TreeNode constructMaximumBinaryTree(int[] nums) {
        TreeNode root = dfsConstruct(nums, 0, nums.length);
        return root;
    }

    private TreeNode dfsConstruct(int[] nums, int start, int end) {
        if (end <= start) {
            return null;
        }
        if (end - start == 1) {
            return new TreeNode(nums[start]);
        }
        int max = Integer.MIN_VALUE;
        int id = -1;
        for (int i = start; i < end; ++i) {
            if (nums[i] > max) {
                max = nums[i];
                id = i;
            }
        }
        TreeNode parent = new TreeNode(max);
        if (id > start) {
            parent.left = dfsConstruct(nums, start, id);
        }
        if (id < end - 1) {
            parent.right = dfsConstruct(nums, id + 1, end);
        }
        return parent;
    }
}
